package com.tsfot.spider.service.impl;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.tsfot.spider.bean.SpiderConfig;
import com.tsfot.spider.bean.SpiderData;
import com.tsfot.spider.exception.CannotCreatDBTableException;
import com.tsfot.spider.service.PersistenceService;
import com.tsoft.database.jda.JDA;

public class PersistenceServiceImpl implements PersistenceService {

	private final static Logger logger=LoggerFactory.getLogger(PersistenceServiceImpl.class);
	
	private SpiderConfig config;
	
	private final static  String SPIDER_TABLE_FIX="spider_";
	
	private JDA jda;
	
	private static int index=0;
	
	
	public void init(){
		if(!exsitsTable()){
			createTable();
		}
	}
	
	private boolean exsitsTable() {
		String tableName=SPIDER_TABLE_FIX+config.getTableName();
		try {
			DatabaseMetaData meta = this.jda.connection().getMetaData();
			ResultSet rsTables = meta.getTables(null , null, tableName, null);
			if(rsTables.next()){
			   System.out.println("The Table exsits.");
			}else{
			   System.out.println("The Table not exsits.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public void saveSpiderData(List<SpiderData> dataList) {
		//创建表结构
		String tableName=SPIDER_TABLE_FIX+config.getTableName();
		try {
			//INSERT INTO `crawl_data_article` ( `title`, `content`, `add_date`, `update_date`, `name`, `href`) VALUES ('1231', '123123', '123123', '1231', '23123', '1231', '2312312')
			StringBuffer sql=new StringBuffer();
			sql.append("INSERT INTO ");
			sql.append(tableName);
			sql.append(" (");
			Map<String, String> dataKeyMap = config.getDataKeyMap();
			List<String> names=Lists.newArrayList();
			for (String name : dataKeyMap.keySet()) {
				sql.append(name+",");
				names.add(name);
			}
			sql.append("ctime )");
			sql.append(" values (");
			for (String name : names) {
				sql.append("?,");
			}
			sql.append("?)");
			//params
			Object[][] params=new Object[dataList.size()][dataKeyMap.size()+1];
			
			for (int i = 0; i < dataList.size(); i++) {
				SpiderData data = dataList.get(i);
				Map<String, String> result = data.getResult();
				int j=0;
				for (String key : names) {
					params[i][j]=result.get(key);
					j++;
				}
				params[i][j]=new Date();
			}
			jda.executeBatch(sql.toString(), params);
		} catch (Exception e) {
			
		}
	}
	
	private void createTable() throws CannotCreatDBTableException {
		StringBuffer sql=new StringBuffer();
		String tableName=SPIDER_TABLE_FIX+config.getTableName();
		sql.append("create table "+tableName);
		sql.append("(");
		sql.append("id int(11) not null primary key auto_increment,");
		Map<String, String> dataKeyMap = config.getDataKeyMap();
		for (String name : dataKeyMap.keySet()) {
			if(name.contains("content")||name.contains("text")||name.contains("intro")){
				sql.append(name+" longtext ,");
			}else{
				sql.append(name+" varchar(255) ,");
				//sql.append(name+" text ,");
			}
		}
		sql.append("ctime datetime null ");
		sql.append(")");
		try {
			jda.execute(sql.toString());
		} catch (Exception e) {
			logger.error("create database table:{} failed! Maybe has exsits!",tableName);
		}
		logger.error("create database table:{} success!",tableName);
	}

	public SpiderConfig getConfig() {
		return config;
	}

	public void setConfig(SpiderConfig config) {
		this.config = config;
	}

	public JDA getJda() {
		return jda;
	}

	public void setJda(JDA jda) {
		this.jda = jda;
	}
	
}
